package com.yfore.jfinal.pdf.plugin;

import java.io.File;
import java.io.IOException;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;



/**
 * ITextRenderer对象工厂
 * @author farmer
 *
 */
public class ITextRendererObjectFactory {
	
	private static ITextRenderer renderer;
	
	/**
	 * 单例创建
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static synchronized ITextRenderer createTextRenderer() {
		if(renderer == null){
			renderer = new ITextRenderer();
		}
		return renderer;
	}


	/**
	 * 添加字体
	 * @param fontResolver
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static ITextFontResolver addFont(String font){
		ITextFontResolver fontResolver = renderer.getFontResolver();
		try {
			fontResolver.addFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fontResolver;
	}
	
	
	/**
	 * 添加目录下的字体
	 * @param fontPath
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static ITextFontResolver addFonts(String fontPath)  {
		ITextFontResolver fontResolver = renderer.getFontResolver();
		File fontsDir = new File(fontPath);
		if (fontsDir != null && fontsDir.isDirectory()) {
			File[] files = fontsDir.listFiles();
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				if (f == null || f.isDirectory()) {
					break;
				}
				try {
					fontResolver.addFont(f.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
				} catch (DocumentException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return fontResolver;
	}
}
